/*
 * @Author: your name
 * @Date: 2021-03-08 13:55:17
 * @LastEditTime: 2021-03-09 10:14:59
 * @LastEditors: Please set LastEditors
 * @Description: longestCommonPrefix
 * @FilePath: \relearnJS\algorithm\最长公共子串.js
 */

//* 1. reduce
function f1(str) {
    if (str === null || str.length === 0) return "";
    return str.reduce((preVal, curVal) => {
        return commonStr(preVal, curVal)
    })

    function commonStr(m, n) {
        var len = m.length,
            i = 0;
        while (i < len && m[i] === n[i]) i++;
        return m.substring(0, i)
    }
};

//* 2. 双层for循环
function f2(str) {
    if (str === null || str.length === 0) return ""
    var prev = str[0];
    for (var i = 1, len = str.length; i < len; i++) {
        for (var j = 0; j < prev.length && j < str[i].length; j++) {
            if (prev.charAt(j) !== str[i].charAt(j)) break
        }
        prev = prev.substring(0, j)
        if (prev === "") return ""
    }
    return prev
}

//* 3. 最长与最短字符串的最大公共前缀
function f3(str) {
    if (str === null || str.length === 0) return ""
    if (str.length === 1) return str[0]
    var min = 0,
        max = 0
    for (var i = 0, len = str.length; i < len; i++) {
        if (str[i] < str[min]) min = i
        if (str[i] > str[max]) max = i
    }
    i = 0
    len = str[min].length
    while (i < len && str[min].charAt(i) === str[max].charAt(i)) i++
    return str[min].substring(0, i)
}